package com.wzxy.medical_backed.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzxy.medical_backed.entity.MedicalCard;
import com.wzxy.medical_backed.entity.Result;
import com.wzxy.medical_backed.service.MedicalCardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/medical-card")
public class MedicalCardController {

    @Autowired
    private MedicalCardService medicalCardService;

    @GetMapping("/getall")
    public Result getAll(@RequestParam(required = false) String keyword,
                         @RequestParam(defaultValue = "1") Integer page,
                         @RequestParam(defaultValue = "10") Integer size) {
        QueryWrapper<MedicalCard> queryWrapper = new QueryWrapper<>();
        if (keyword != null && !keyword.isEmpty()) {
            queryWrapper.like("card_id", keyword)
                    .or().like("insured_name", keyword)
                    .or().like("medical_name", keyword);
        }
        IPage<MedicalCard> cardPage = medicalCardService.page(new Page<>(page, size), queryWrapper);
        return new Result("查询成功", cardPage, 200);
    }

    @PostMapping("/add")
    public Result add(@RequestBody MedicalCard medicalCard) {
        boolean saved = medicalCardService.save(medicalCard);
        return saved ? new Result("添加成功", null, 200) : new Result("添加失败", null, 500);
    }

    @PostMapping("/update")
    public Result update(@RequestBody MedicalCard medicalCard) {
        boolean updated = medicalCardService.updateById(medicalCard);
        return updated ? new Result("更新成功", null, 200) : new Result("更新失败", null, 500);
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        boolean removed = medicalCardService.removeById(id);
        return removed ? new Result("删除成功", null, 200) : new Result("删除失败", null, 500);
    }
}